<template>
  <div class="coupon">
    <!-- 筛选头部 -->
    <div class="search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo" class="search-form">
        <el-form-item label="优惠券码：">
          <el-input v-model="searchInfo.id" size="medium" placeholder="请输入优惠券码" />
        </el-form-item>
        <el-form-item label="优惠券名称：">
          <el-input v-model="searchInfo.searchName" size="medium" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券状态：">
          <el-select v-model="searchInfo.type" size="medium" placeholder="请选择优惠券使用时效状态">
            <el-option label="使用时效期前" :value="2" />
            <el-option label="使用时效期内" :value="0" />
            <el-option label="已过期" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="primary" icon="el-icon-search" size="medium" @click="toSearch">查询</el-button>
          <el-button size="medium" @click="resetSearchInfo">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 优惠券列表 -->
    <div class="ad-list-wrapper">
      <div class="ad-list">
        <div class="ad-list-func">
          <div>
            <el-checkbox v-model="checkedAll" @change="checkAll">全部</el-checkbox>
            <el-button class="button" icon="el-icon-delete" size="small" @click="deleteMany">批量删除</el-button>
            <p class="selected-num">已选择 <span>{{ checkedCount }}</span> 项</p>
            <el-button type="text" @click="clearAll">清空</el-button>
          </div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="dialogVisible = true">添加优惠券</el-button>
        </div>
        <div v-if="list.length === 0" class="none">
          你还没有添加优惠券～
        </div>
        <table v-else v-loading="loading" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <th class="checkbox">选择</th>
              <th class="index">序号</th>
              <th class="code">优惠券码</th>
              <th>优惠券名称</th>
              <th class="value">面值</th>
              <th class="requirement">消费条件</th>
              <th>使用时限</th>
              <th>生成时间</th>
              <th>领取/发行量</th>
              <th class="state">状态</th>
              <th class="func">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(coupon, index) in list" :key="coupon.id" class="list-item">
              <td class="check"><el-checkbox v-model="coupon.selected" @change="checkItem" /></td>
              <td>{{ (index + 1 + pageSize * ( currentPage - 1 )) | addZeroPrefix }}</td>
              <td>{{ coupon.id }}</td>
              <td class="name">{{ coupon.name }}</td>
              <td class="value">{{ coupon.value | fixedPrice }}</td>
              <td>{{ coupon.condition | fixedPrice }}</td>
              <td>{{ new Date(coupon.usedStartDate) | getDate }}至{{ new Date(coupon.usedEndDate) | getDate }}</td>
              <td class="create-date">{{ new Date(coupon.createDate) | getDate }} {{ new Date(coupon.createDate) | getTime }} </td>
              <td class="used"><span>{{ coupon.used }}</span> / {{ coupon.count }}</td>
              <td v-if="now < Number(coupon.usedStartDate)" class="state dis">使用时效期前</td>
              <td v-else-if="now > Number(coupon.usedEndDate)" class="state dis">已过期</td>
              <td v-else class="state">使用时效期内</td>
              <td>
                <el-button type="text" @click="openDetail(coupon)">查看</el-button>
                <el-divider direction="vertical" />
                <el-button type="text" @click="handleDelete(coupon.id)">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="couponCount"
          :hide-on-single-page="true"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 增加弹框 -->
    <el-dialog
      v-el-drag-dialog
      width="30%"
      :visible.sync="dialogVisible"
      class="edit-dialog"
      center
      hide-required-asterisk
    >
      <template v-loading="addLoading">
        <h2 slot="title" class="dialog-title">添加优惠券</h2>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="demo-form">
          <el-form-item label="优惠券名称：" prop="name" required>
            <el-input v-model="form.name" size="medium" placeholder="请填写优惠券名称" />
          </el-form-item>
          <el-form-item label="优惠券面值：" prop="value" required>
            <el-input v-model.number="form.value" size="medium" placeholder="优惠券面值："> <template slot="suffix">元</template></el-input>
          </el-form-item>
          <el-form-item label="消费条件：" prop="condition" required>
            <el-input v-model.number="form.condition" size="medium" placeholder="例：单笔满200元,就填200"> <template slot="suffix">元</template></el-input>
          </el-form-item>
          <el-form-item label="发行数量：" prop="count" required>
            <el-input v-model.number="form.count" size="medium" placeholder="请输入发行数量"> <template slot="suffix">张</template></el-input>
          </el-form-item>
          <el-form-item label="领取日期：" required>
            <el-date-picker
              v-model="form.receiveDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="medium"
              value-format="timestamp"
            />
          </el-form-item>
          <el-form-item label="使用日期：" required>
            <el-date-picker
              v-model="form.useDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="medium"
              value-format="timestamp"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="add">确 认</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 查看弹框 -->
    <el-dialog
      v-el-drag-dialog
      width="30%"
      :visible.sync="detailDialogVisible"
      class="edit-dialog detail-dialog"
      center
      hide-required-asterisk
    >
      <h2 slot="title" class="dialog-title">优惠券详情</h2>
      <div class="box">
        <div class="top">
          <div>
            <p><span class="label">优惠券码：</span><span class="value">{{ detail.id }}</span></p>
            <p><span class="label">创建时间：</span><span class="value">{{ new Date(detail.createDate) | getDate }} {{ new Date(detail.createDate) | getTime }}</span></p>
          </div>
        </div>
        <div class="bottom">
          <div>
            <p class="line"><span class="label">优惠券名称：</span><span class="value">{{ detail.name }}</span></p>
          </div>
          <div>
            <p><span class="label">优惠券面值：</span><span class="value">{{ detail.value | fixedPrice }}</span></p>
            <p><span class="label">消费条件：</span><span class="value">{{ detail.condition | fixedPrice }}</span></p>
          </div>
          <div>
            <p><span class="label">已领/发行量：</span><span class="value">{{ detail.received }}/{{ detail.count }} 张</span></p>
            <p><span class="label">已使用：</span><span class="value">{{ detail.used }} 张</span></p>
          </div>
          <div>
            <p class="line"><span class="label">领取时间：</span><span class="value">{{ new Date(detail.receiveStartDate) | getDate }} 至 {{ new Date(detail.receiveEndDate) | getDate }}</span></p>
          </div>
          <div>
            <p class="line"><span class="label">使用时间：</span><span class="value">{{ new Date(detail.usedStartDate) | getDate }} 至 {{ new Date(detail.usedEndDate) | getDate }}</span></p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getList, add, del } from '@/api/coupon';
import { mapGetters } from 'vuex';
export default {
  name: 'CouponList',
  data() {
    return {
      now: Number(new Date().getTime()),
      loading: false,
      addLoading: false,
      dialogVisible: false,
      detailDialogVisible: false,
      rules: {
        name: [
          { required: true, message: '请填写优惠券名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请填写优惠券面值', trigger: 'blur' },
          { type: 'number', message: '优惠券面值必须为数字值', trigger: 'blur' }
        ],
        count: [
          { required: true, message: '请填写优惠券数量', trigger: 'blur' },
          { type: 'number', message: '优惠券数量必须为数字值', trigger: 'blur' }
        ],
        condition: [
          { required: true, message: '请填写消费条件', trigger: 'blur' },
          { type: 'number', message: '消费条件必须为数字值', trigger: 'blur' }
        ],
        receiveDate: [
          { required: true, message: '请选择领取日期', trigger: 'change' }
        ],
        useDate: [
          { required: true, message: '请选择使用日期', trigger: 'change' }
        ]
      },
      searchInfo: {
        searchName: '',
        id: '',
        type: ''
      },
      form: {
        name: '',
        value: null,
        condition: null,
        count: null,
        receiveDate: [new Date(), new Date()],
        useDate: [new Date(), new Date()]
      },
      detail: {
        name: '',
        value: null,
        condition: null,
        count: null,
        receiveDate: [new Date(), new Date()],
        useDate: [new Date(), new Date()]
      },
      list: [],
      checkedAll: false,
      checkedCount: 0,

      // 分页
      currentPage: 1,
      pageSize: 5,
      couponCount: 1
    };
  },
  computed: {
    ...mapGetters(['shopInfo'])
  },
  watch: {
    checkedCount(value) {
      this.checkedAll = value === this.list.length;
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    // {“id”:”优惠券id”,”searchName”:”搜索名字”,”shopId”:””,”type”:”0进行中 1已过期”}
    getList() {
      this.loading = true;
      const shopId = this.shopInfo.id;
      const pageNo = this.currentPage;
      const pageSize = this.pageSize;
      const { id, searchName, type } = this.searchInfo;
      new Promise((resolve, reject) => {
        getList({ shopId, id, searchName, type, pageNo, pageSize }).then(res => {
          const list = res.data.coupons;
          list.forEach(item => {
            item.selected = false;
          });
          this.list = list;
          this.couponCount = res.data.size;
          this.loading = false;
          this.dialogVisible = false;
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    /**
     * @param {*} data
     * name;// 优惠券名字
     * value;// 优惠券面值
     * condition;// 消费条件
     * count;// 发行数量
     * receiveStartDate;// 领取开始时间
     * receiveEndDate;// 领取结束时间
     * usedStartDate;// 使用开始时间
     * usedEndDate;// 使用结束时间
     */
    add() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          const shopId = this.shopInfo.id;
          const { name, value, condition, count, receiveDate, useDate } = this.form;
          const receiveStartDate = receiveDate[0];
          const receiveEndDate = receiveDate[1];
          const usedStartDate = useDate[0];
          const usedEndDate = useDate[1];
          new Promise((resolve, reject) => {
            add({ shopId, name, value: Number(value) * 100, condition: Number(condition) * 100, count, receiveStartDate, receiveEndDate, usedStartDate, usedEndDate }).then(res => {
              this.$message({
                type: 'success',
                message: '添加成功'
              });
              Object.assign(this.$data.form, this.$options.data().form);
              this.dialogVisible = false;
              this.addLoading = false;
              this.getList();
              resolve(res);
            }).catch(err => {
              reject(err);
            });
          });
        } else {
          this.$message({
            type: 'error',
            message: '请按规则填写优惠券信息'
          });
          return false;
        }
      });
    },
    // {“id”:”1/2/3”,”flag”:”1”}
    del(id) {
      new Promise((resolve, reject) => {
        del({ id, flag: '1' }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功'
          });
          this.clearAll();
          this.getList();
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    toSearch() {
      this.getList();
    },
    resetSearchInfo() {
      Object.assign(this.$data.searchInfo, this.$options.data().searchInfo);
    },
    checkAll(value) {
      this.checkedCount = value ? this.list.length : 0;
      this.list.forEach(coupon => {
        coupon.selected = value;
      });
    },
    checkItem(value) {
      value ? this.checkedCount++ : this.checkedCount--;
    },
    clearAll() {
      if (this.checkedCount === 0) return;
      this.checkedCount = 0;
      this.checkedAll = false;
      this.list.forEach(coupon => {
        coupon.selected = false;
      });
    },
    // 批量删除
    deleteMany() {
      if (this.checkedCount === 0) {
        this.$message({
          message: '请选择您要删除的优惠券',
          type: 'warning'
        });
        return false;
      }
      const selectedIdList = [];
      this.list.filter(coupon => {
        return coupon.selected;
      }).map(coupon => {
        selectedIdList.push(coupon.id);
      });
      this.$confirm('此操作将永久删除该优惠券, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.del(selectedIdList.join('/'));
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    openDetail(coupon) {
      this.detail = coupon;
      this.detailDialogVisible = true;
    },
    // 删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除该优惠券, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.del(id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.coupon{
  font-size: $fontSizeBase;
  color: $textColorDark;
  min-height: calc(100vh - 70px - 84px - 40px);
}
.ad-list-wrapper{
  min-height: calc(100vh - 70px - 84px - 40px - 90px);
}
@import '@/styles/shop-activity.scss';
.ad-list {
  table {
    th,td{
      &:first-child,
      &:nth-child(2),
      &:nth-child(3){
        text-align: center;
      }
    }
    td{
      padding: 40px 10px;
      &.check{
        padding-left: 10px;
      }
      &.name,&.used span,&.state{
        font-weight: bolder;
      }
      &.value{
        color: #F56A6D;
      }
      &.create-date,&.state.dis{
        color: #838A9D;
      }
    }
  }
}
.edit-dialog{
  h2{
    margin: 0;
    text-align: left;
  }
  /deep/ .el-dialog__header{
    border-bottom: 1px solid $borderColor;
  }
  /deep/ .el-dialog{
    max-width: 530px;
  }
  /deep/ .el-date-editor{
    width: 100%;
  }
}
.detail-dialog{
  span{
    display: inline-block;
  }
  .label{
    width: 95px;
    text-align: right;
    color: $textColorBase;
  }
  .value{
    color: $textColorDark;
  }
  .top,.bottom{
    &>div{
      display: flex;
      align-items: center;
      p{
        flex: 0 0 50%;
        &.line{
          flex: 1;
        }
      }
    }
  }
  .top{
    background-color: #E8F1FF;
    height: 50px;
    line-height: 50px;
  }
  .bottom{
    margin-top: 20px;
    &>div{
      border: 1px solid $borderColor;
      border-top: 0;
      height: 60px;
      line-height: 60px;
      &:first-child{
        border-top: 1px solid $borderColor;
      }
    }
  }
}
</style>
